import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';

interface BarProps {
  title: string;
  xData: string[];
  yData: number[];
  style: React.CSSProperties;
}

const Bar: React.FC<BarProps> = ({ title, xData, yData, style }: BarProps) => {
  const domRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    chartInit();
  }, []);

  const chartInit = () => {
    if (domRef.current) {
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(domRef.current);

      // 绘制图表
      myChart.setOption({
        title: {
          text: title
        },
        legend: {
          data: ["衬衫", "羊毛衫", "雪纺衫", "高跟鞋"]
        },
        tooltip: {},
        xAxis: {
          data: xData,
          // 设置左上角统计项
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: {},
        series: [
          {
            name: '衬衫',
            type: 'bar',
            data: yData
          },
          {
            name: '羊毛衫',
            type: 'bar',
            data: yData
          },
          {
            name: '雪纺衫',
            type: 'bar',
            data: yData
          }
        ]
      });
    }
  };

  return (
    <div>
      {/* 挂载节点 */}
      <div ref={domRef} style={style}></div>
    </div>
  );
};

export default Bar;
